<template>
  <div class="user-managment-page">
    <div class="operation-bar">
      <el-button
          type="danger"
          icon="el-icon-delete"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0">批量删除选中用户
      </el-button>
    </div>
    <div class="search-area">
      <el-form inline :model="searchForm" ref="searchForm">
        <el-form-item label="用户名">
          <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              clearable>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getUserList">搜索</el-button>
        </el-form-item>
        <el-form-item>
          <el-button plain @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
        :data="tableData"
        style="width: 100%"
        border
        empty-text="暂无数据"
        row-key="id"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="password" label="密码"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="createTime" label="注册时间"></el-table-column>
      <el-table-column prop="money" label="余额"></el-table-column>
      <el-table-column prop="sex" label="性别" :formatter="formatGender"></el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button
              type="text"
              size="small"
              style="color: #F56C6C;"
              @click="handleSingleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'UserManagment',
  data() {
    return {
      tableData: [],
      selectedRows: [],
      searchForm: {
        username: '',
        phone: '',
        createTime: []
      }
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 表格选中事件：更新选中的行
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    // 1. 获取用户列表
    async getUserList() {
      try {
        const params = {
          username: this.searchForm.username.trim()
        }
        const res = await axios.get('http://localhost:8080/api/findUserByUsernameLike', {
          params,
          timeout: 5000
        });

        if (res.data && res.data.code === 200) {
          this.tableData = res.data.data || []
        } else {
          this.tableData = []
          this.$message.error('获取数据失败：' + (res.data?.msg || '未知错误'))
        }
      } catch (error) {
        this.tableData = []
        console.error('请求错误：', error)
        this.$message.error('网络错误，请检查后端是否正常运行')
      }
    },

    // 2. 单行删除
    async handleSingleDelete(row) {
      if (!row || !row.id) {
        this.$message.error('用户ID缺失，无法删除');
        return;
      }

      const confirmResult = await this.$confirm(
          `确定要删除用户【${row.username}】吗？删除后不可恢复！`,
          '删除确认',
          {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).catch(() => 'cancel')

      if (confirmResult === 'confirm') {
        try {
          this.$message.info('正在删除用户...')
          const res = await axios.post(`http://localhost:8080/api/deleteUser?id=${row.id}`);
          if (res.data && res.data.code === 200) {
            this.$message.success('删除用户成功！')
            this.selectedRows = []
            await this.getUserList()
          } else {
            this.$message.error('删除失败：' + (res.data?.msg || '后端未返回原因'))
          }
        } catch (error) {
          console.error('删除请求错误：', error)
          this.$message.error('网络错误，删除失败（请检查后端接口）')
        }
      }
    },

    // 3. 批量删除（修复：增加校验+确认弹窗+正确参数拼接）
    async handleBatchDelete() {
      // 校验1：是否选中用户
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选中要删除的用户');
        return;
      }

      // 校验2：是否有ID缺失的行
      const invalidRows = this.selectedRows.filter(row => !row.id);
      if (invalidRows.length > 0) {
        this.$message.error(`部分用户ID缺失（共 ${invalidRows.length} 个），请刷新后重试`);
        return;
      }

      // 提取ID数组并拼接URL参数
      const userIds = this.selectedRows.map(row => row.id);
      console.log("要删除的IDs：", userIds); // 调试用，可查看ID是否正确
      const idsParam = userIds.join('&ids='); // 转换为 "1&ids=2&ids=3"
      const url = `http://localhost:8080/api/batchDeleteUser?ids=${idsParam}`;

      // 二次确认弹窗
      const confirmResult = await this.$confirm(
          `确定删除选中的 ${this.selectedRows.length} 个用户？删除后不可恢复！`,
          '确认删除',
          { type: 'danger' }
      ).catch(() => 'cancel');

      if (confirmResult === 'confirm') {
        try {
          this.$message.info('正在批量删除用户...')
          const res = await axios.post(url); // 发送带参数的POST请求
          if (res.data && res.data.code === 200) {
            this.$message.success('批量删除成功！')
            this.selectedRows = [] // 清空选中状态
            await this.getUserList() // 刷新表格
          } else {
            this.$message.error('批量删除失败：' + (res.data?.msg || '后端未返回原因'))
          }
        } catch (error) {
          console.error('批量删除错误：', error);
          this.$message.error('网络错误或参数传递失败（请检查后端接口）');
        }
      }
    },
    formatGender(row) {
      const sex = row.sex;
      return sex === 1 ? '男' : sex === 2 ? '女' : '未知';
    },
    resetForm() {
      this.$refs.searchForm.resetFields() // 重置表单
      this.getUserList() // 重置后重新查询
    }
  }
}
</script>

<style scoped>
.user-managment-page {
  padding: 20px;
}
.search-area {
  margin-bottom: 20px;
}
.operation-bar {
  margin-bottom: 20px; /* 增加操作栏与搜索区的间距，更美观 */
}
</style>